import React, { useMemo, CSSProperties } from 'react';
import { Image as ImageComponent } from '@tarojs/components';
import './index.scss';
import { ImageProps } from '../../../types/components/image';
const webp = 'image/auto-orient,1/quality,q_100/format,webp';

/**
 * Image 图片组件
 */
const Image: React.FC<ImageProps> = ({
  autoCalcSize = true,
  scale = 1,
  ...props
}) => {
  let uriSource = props.src;

  const finalSource = useMemo(() => {
    let flattenStyle = props.style as CSSProperties;
    let imageWidth = (flattenStyle && (flattenStyle.width as number)) || 300;
    imageWidth = Math.floor(imageWidth);
    if (isNaN(imageWidth)) {
      imageWidth = 600;
    }
    let uri = uriSource;
    if (
      uri &&
      uri.startsWith('http') &&
      (uri.indexOf('yryz.com') != -1 ||
        uri.indexOf('yryz2.com') != -1 ||
        uri.indexOf('lajsf.com') != -1)
    ) {
      if (uri.indexOf('visitcard/images/') != -1) return uri;
      if (uri.indexOf('gif') != -1) return uri;
      if (autoCalcSize) {
        let param = `x-oss-process=image/resize,m_lfit,h_0,w_${imageWidth *
          scale}`;
        uri += `${uri.includes('?') ? '&' : '?'}${param}`;
      }

      if (uri.includes('x-oss-process')) {
        uri += ',' + webp;
      } else {
        uri += (uri.includes('?') ? '&' : '?') + 'x-oss-process=' + webp;
      }

      let finalSource: string = uri;
      return finalSource;
    }

    return uriSource;
  }, [uriSource, autoCalcSize, props.style]);

  return <ImageComponent lazyLoad {...props} webp={true} src={finalSource} />;
};

export default Image;
